package com.xwltz.core.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * @description FileUtils
 * @information on version 1.0 be created by @xwltz at 2021/12/29 16:21
 */
@SuppressWarnings("unused")
public class FileUtils {
	// @Value("${framework.upload-file-path}")
	public static String DEFAULT_FILE = "uploads";
	public static String FILE_STORAGE_ROOT = getRootPath();
	private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

	private static String getRootPath() {
		try {
			Resource resource = new ClassPathResource("");
			return resource.getFile().getAbsolutePath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * description: 文件上传
	 * information: on version 1.0 be created by xwltz at 2021/12/29 16:27
	 *
	 * @param multipartFile multipartFile
	 * @return String
	 * @throws FileNotFoundException ex
	 */
	public String upload(CommonsMultipartFile multipartFile) throws FileNotFoundException {
		String storageRoot = ResourceUtils.getURL("classpath:").getPath() + DEFAULT_FILE;

		String path = "";
		String suffix = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf("."));
		String fileName = SIMPLE_DATE_FORMAT.format(new Date()) + "-" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase() + suffix;
		File file = new File(storageRoot + File.separator + DEFAULT_FILE + File.separator + fileName);
		if (!file.getParentFile().exists()) {
			boolean wasSuccessful = file.getParentFile().mkdirs();
		}
		try {
			multipartFile.transferTo(file);
			path = File.separator + DEFAULT_FILE + File.separator + fileName;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return path;
	}

	/**
	 * description: 删除文件
	 * information: on version 1.0 be created by xwltz at 2021/12/29 16:27
	 *
	 * @param url url
	 * @return boolean
	 */
	public boolean remove(String url) {
		File file = new File(url);
		if (file.exists() && file.isFile()) {
			return file.delete();
		}
		return false;
	}

	/**
	 * description: 删除多文件
	 * information: on version 1.0 be created by xwltz at 2021/12/29 16:27
	 *
	 * @param urls urls
	 */
	public void remove(Collection<String> urls) {
		if (!CollectionUtils.isEmpty(urls)) {
			boolean wasSuccessful = urls.stream().allMatch(this::remove);
		}
	}
}
